<template>
  <div class="">
    <ContentWrap :show-border="false">
      <SearchBox
        :queryForm="searchList"
        :showExpland="false"
        @changeVal="handleChange"
        @query="handleSearchQuery"
        :show-export="false"
        :show-len="4"
      />
    </ContentWrap>
  </div>

  <div class="mt-[30px] flex items-center">
    <div
      class="bg w-[14px] h-[14px] mr-[5px]"
      style="
        background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN01eYDHP42Ipwk9q9ztR_!!801089336.png);
      "
    ></div>

    已选 <span class="text-[#3721FF]">{{ ids.length }}</span> 项
    <el-button
      type="primary"
      @click="handleBtnClick({ type: 'add' })"
      round
      color="rgba(55,33,255,1)"
      style="color: #fff"
      class="ml-[10px]"
    >
      新增
    </el-button>

    <el-button
      type="primary"
      @click="handleBtnClick({ type: 'del' })"
      round
      s-ze="large"
      color="rgba(55,33,255,0.06)"
      style="color: #101010"
      class="ml-[10px] w-[96px]"
    >
      批量删除
    </el-button>
  </div>

  <!-- 列表 -->
  <div class="mt-[30px]">
    <QueryTable
      :list="list"
      :total="total"
      :btns="tableBtnList"
      pk="id"
      @execute="handleBtnClick"
      v-model="queryParams"
      :thead="th"
      :show-action="true"
    >
      <template #createTime="{ row }">
        <!-- <div class="flex items-center">
          <div class="mr-[20px]">{{ row.createName }}</div>

          <div>
            <div>创建时间：{{ row.createTime }}</div>
            <div>更新时间：{{ row.createTime }}</div>
          </div>
        </div> -->
        <div>
          <div class="flex items-center">
            创建时间：{{ formatTime(row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
          </div>
          <div class="flex items-center">
            更新时间：{{ formatTime(row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
          </div>
        </div>
      </template>

      <template #accessToken="{ row }">
        <div class="text-line2" :title="row.accessToken">{{ row.accessToken }}</div>
      </template>
    </QueryTable>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <!--  <AppSocialForm ref="formRef" @success="getList"/>-->

  <InfoAction v-model="isShowDialog" :info="selectRows" @confirm="handleBtnClick" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AppSocialApi, AppSocialVO } from '@/api/ad/appSocial'
import AppSocialForm from './AppSocialForm.vue'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import ImagePreview from '@/components/ImagePreview/index.vue'
import QueryTable from '@/components/TableData/index.vue'
import Icon from '../../../components/Icon/src/Icon.vue'
import InfoAction from './components/InfoAction.vue'
import { getSimpleDeptList } from '@/api/system/dept'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'
import { throttle, buildTree, formatTime } from '@/utils'
import dayjs from 'dayjs';

/** facebook广告应用 列表 */
defineOptions({ name: 'AppSocial' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AppSocialVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

const depatList = ref([])

const createNameList = ref([])

const th = ref([
  {
    name: '应用名称',
    code: 'appName'
  },
  {
    name: 'app_id',
    code: 'appId'
  },
  {
    name: 'app_secret',
    code: 'appSecret'
  },
  {
    name: 'access_token',
    code: 'accessToken'
  },
  {
    name: '部门',
    code: 'deptName'
  },
  {
    name: '人员',
    code: 'createName'
  },
  {
    name: '创建时间',
    code: 'createTime'
  }
])

const ids = ref<any[]>([])

const initRow = {}
const selectRows = ref({ ...initRow })
const isShowDialog = ref(false)

const tableBtnList = ref([
  {
    color: '#3721FF',
    code: 'edit',
    name: '编辑'
  },
  {
    color: '#FF4E00',
    code: 'delItem',
    name: '删除'
  }
])

const initQueryParams = {
  pageNo: 1,
  pageSize: 10,
  appSecret: undefined,
  appName: undefined,
  accessToken: undefined,
  deptId: undefined,
  createName: undefined,
  createTime: []
}

const queryParams = ref({
  ...initQueryParams,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const searchList = ref<TradeOrderQueryVO[]>([
  {
    label: '部门',
    code: 'deptId',
    type: 'treeSelect',
    options: depatList.value
  },
  {
    label: '人员',
    code: 'createName',
    type: 'select',
    options: createNameList.value
  },
  {
    label: '应用名称',
    code: 'appName',
    type: 'input'
  },
  {
    label: 'app_id',
    code: 'appId',
    type: 'input'
  }
])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AppSocialApi.getAppSocialPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AppSocialApi.deleteAppSocial(id)
    message.success(t('删除成功'))
    // 刷新列表
    queryParams.value.pageNo = 1
    await getList()
  } catch {}
}
/** 批量删除按钮操作 */
const handleDeleteBatch = async (id: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AppSocialApi.deleteAppSocialBatch(id.join(','))
    message.success(t('删除成功'))
    // 刷新列表
    queryParams.value.pageNo = 1
    await getList()
  } catch {}
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AppSocialApi.exportAppSocial(queryParams.value)
    download.excel(data, 'facebook广告应用.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleBtnClick = (e) => {
  let type = e.type
  console.log('e', e)
  try {
    fn[type](e)
  } catch (e) {
    console.log(e)
    console.log(`${type}不存在`)
  }
}

const fn = {
  appSocialConfirm: throttle(async ({ data }) => {
    if (data.id) {
      await AppSocialApi.updateAppSocial(data)
    } else {
      await AppSocialApi.createAppSocial(data)
    }
    getList()
  }, 1000),
  selectionChange({ data }) {
    ids.value = data.ids
  },
  add() {
    selectRows.value = {
      ...initRow
    }
    isShowDialog.value = true
  },
  async del() {
    if (ids.value.length == 0) {
      message.error('请选择要删除的数据')
      return
    }
    handleDeleteBatch(ids.value)
  },
  delItem({ data: { row } }) {
    handleDelete(row.id)
  },
  edit({ data: { row } }) {
    selectRows.value = row
    isShowDialog.value = true
  }
}

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */

  queryParams.value = {
    ...initQueryParams,
    ...val
  }
  getList()
}

const handleChange = (val) => {
  if (val.form.deptId) {
    queryParams.value.deptId = val.form.deptId
  }
}
watch(
  () => queryParams.value.deptId,
  () => {
    getCreateNameList()
  }
)
//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99, deptId: queryParams.value.deptId })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.nickname
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'createName') {
      item.options = createNameList.value
    }
  })
}

const init = async () => {
  const [depatRes] = await Promise.all([getSimpleDeptList()])
  depatList.value = buildTree(depatRes)
  searchList.value.map((item) => {
    if (item.code === 'deptId') {
      item.options = depatList.value
    }
  })
}

/** 初始化 **/
onMounted(() => {
  init()
  getList()
})
</script>
<style lang="scss" scoped>
.scrollbox {
  overflow-x: auto; /* 允许横向滚动 */
}
:deep(.el-table.myTable thead tr) {
  background-color: #f7f7fb;
  border-radius: 4px;
  overflow: hidden;
}
:deep(.el-table.myTable thead th.el-table__cell) {
  background-color: #f7f7fb;
}
:deep(.el-button) {
  height: 45px !important;
  border-radius: 23px !important;
  padding: 0 22px !important;
}
</style>
